<template>
  <a-modal :visible="visible" @cancel="cancelBtn" :title="title">
    <template #footer>
      <a-row type="flex" justify="space-between">
        <a-col>
          <a-button @click="downloadUrl"
            ><DownloadOutlined />模板下载</a-button
          ></a-col
        >
        <a-col>
          <a-button @click="cancelBtn">取消</a-button>
          <a-button type="primary" :loading="loading" @click="handleOk"
            >确认</a-button
          >
        </a-col>
      </a-row>
    </template>
    <a-alert
      class="alert-box"
      v-if="['contract', 'bill'].includes(from)"
      :message="`单次最多导入${from=='contract'?'50':'200'}条数据`"
      type="info"
      show-icon
    />
    <!-- :action="$utils.localFileAction" -->
    <a-upload-dragger
      :fileList="fileList"
      :multiple="false"
      :before-upload="beforeUpload"
      accept=".xlsx"
      @remove="handleRemove"
    >
      <p class="ant-upload-drag-icon">
        <inbox-outlined></inbox-outlined>
      </p>
      <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
      <p class="ant-upload-hint">支持扩展名: .xlsx</p>
    </a-upload-dragger>
    <div class="switch-box" v-if="from === 'department'">
      自动生成部门
      <TextTip
        tips="如果勾选是，当表格中的部门不存在时，则自动创建。第一级部门必须是公司名。"
      />
      <a-switch
        class="ml-10"
        v-model:checked="checked"
        :checkedValue="1"
        :unCheckedValue="0"
        checked-children="是"
        un-checked-children="否"
      />
    </div>
    <div class="switch-box" v-if="from === 'contract'">
      自动生成账单
      <TextTip tips="如果不勾选则不会自动生成账单，请后续自行导入账单。" />
      <a-switch
        class="ml-10"
        v-model:checked="isNewBill"
        :checkedValue="1"
        :unCheckedValue="0"
        checked-children="是"
        un-checked-children="否"
      />
    </div>
  </a-modal>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  watch,
  createVNode,
  h,
} from "vue";
import {
  InboxOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import request from "../../../../common/utils/request";
import { Modal } from "ant-design-vue";
import { TextTip } from "bl-common-vue3";
export default defineComponent({
  name: "Import",
  components: { InboxOutlined, DownloadOutlined, TextTip },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 导入的request
    importUrl: {
      type: Object,
      default: () => ({
        server: "/org",
        url: "/department/user/import",
      }),
    },
    // 标识
    from: {
      type: String,
      default: "department",
    },
    // 下载模板
    downloadTemUrl: {
      type: Object,
      default: () => ({
        server: "/org",
        url: "/department/user/import/demo",
      }),
    },
    // 下载模板的方式
    downloadTemType: {
      type: String,
      default: "normal",
    },
    title: {
      type: String,
      default: "导入成员",
    },
    showError: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    const checked = ref(0);
    const loading = ref(false);
    const isNewBill = ref(1);

    const cancelBtn = () => {
      context.emit("cancelBtn");
    };
    const handleOk = () => {
      loading.value = true;
      const formData = new FormData();
      formData.append("file", fileList.value[0]);
      if (props.from === "department") {
        formData.append("auto_department", checked.value);
      }
      if (props.from === "contract") {
        formData.append("status", isNewBill.value);
      }
      if (["contract", "bill", "invoice", "receipt"].includes(props.from)) {
        formData.append("throw", 1);
      }
      request
        .post(props.importUrl.server, props.importUrl.url, formData)
        .then((res) => {
          loading.value = false;
          if (props.showError) {
            if (res.fileUrl) {
              Modal.confirm({
                title: "导入错误",
                icon: createVNode(ExclamationCircleOutlined),
                content: () =>
                  h("div", { style: "color:#666;" }, [
                    h("div", {}, `有误条数: ${res.errorRow} `),
                    h(
                      "div",
                      {},
                      " 请下载反馈文档，导入结果可以帮助您更快锁定问题"
                    ),
                  ]),
                okText: "下载文档",
                cancelText: "返回",
                onOk() {
                  let info = {
                    type: "selectDownloadFiles",
                    url: res.fileUrl,
                  };
                  window.microApp.forceDispatch(info);
                },
              });
              loading.value = false;
              return;
            }
            message.success("导入成功");
            fileList.value = [];
            context.emit("refresh");
            loading.value = false;
          } else {
            loading.value = false;
            fileList.value = [];
            if (props.from === "department") {
              checked.value = 0;
            }
            if (props.from === "contract") {
              isNewBill.value = 1;
            }
            context.emit("success", res);
          }
        })
        .catch((err) => {
          loading.value = false;
        });
    };

    //下载模板
    const iframe = document.createElement("iframe");
    const downloadUrl = () => {
      if (props.downloadTemType === "normal") {
        request
          .get(props.downloadTemUrl.server, props.downloadTemUrl.url)
          .then((res) => {
            iframe.src = res.fileUrl;
            iframe.style.display = "none";
            document.body.appendChild(iframe);
            setTimeout(() => {
              document.body.removeChild(iframe);
            }, 1000);
          });
      }
      if (props.downloadTemType === "downLoad") {
        request
          .downLoad(props.downloadTemUrl.server, props.downloadTemUrl.url)
          .then((res) => {
            let url = window.URL.createObjectURL(new Blob([res.data]));
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", res.fileName || "excel.xlsx");

            document.body.appendChild(link);
            link.click();
            link.remove();
          });
      }
    };

    // 导入房源
    const fileList = ref([]);
    const beforeUpload = (file) => {
      fileList.value = [file];
      return false;
    };
    // 移除文件
    const handleRemove = (file) => {
      const index = fileList.value.indexOf(file);
      const newFileList = fileList.value.slice();
      newFileList.splice(index, 1);
      fileList.value = newFileList;
    };

    watch(
      () => props.visible,
      (val) => {
        if (!val) {
          fileList.value = [];
          checked.value = 0;
          isNewBill.value = 1;
          loading.value = false;
        }
      }
    );

    return {
      checked,
      loading,
      isNewBill,
      beforeUpload,
      handleRemove,
      handleOk,
      cancelBtn,
      fileList,
      downloadUrl,
    };
  },
});
</script>

<style lang="less" scoped>
.switch-box {
  margin-top: 12px;
  height: 30px;
  display: flex;
  align-items: center;
}
.alert-box {
  margin-bottom: 16px;
}
.ml-10 {
  margin-left: 10px;
}
</style>
